<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="贷款编号" prop="loaNo">
        <el-input
          v-model="queryParams.loaNo"
          placeholder="请输入贷款编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批人" prop="exaName">
        <el-input
          v-model="queryParams.exaName"
          placeholder="请输入审批人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批时间" prop="exaTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.exaTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择审批时间"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="exaState">
        <el-select
          v-model="queryParams.exaState"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in exaStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮栏（仅保留导出和搜索显示切换） -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:examine:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格（移除选择框和删除操作列，修复贷款编号显示） -->
    <el-table v-loading="loading" :data="examineList">
      <el-table-column label="编号" align="center" prop="exaId" />
      <!-- 修复：通过贷款ID关联贷款编号 -->
      <el-table-column label="贷款编号" align="center">
        <template slot-scope="scope">
          {{ getLoaNoByLoaId(scope.row.exaLoaId) || "未关联贷款" }}
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="exaName" />
      <el-table-column label="审批时间" align="center" prop="exaTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exaTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="exaState">
        <template slot-scope="scope">
          <dict-tag :options="exaStateOptions" :value="scope.row.exaState"/>
        </template>
      </el-table-column>
      <el-table-column label="审批理由" align="center" prop="exaRemark" />
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listExamine, exportExamine } from "@/api/system/examine";
import { getLoansNo } from "@/api/system/loans";

export default {
  name: "Examine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 贷款列表（用于关联贷款ID和贷款编号）
      loansNoOptions: [],
      // 总条数
      total: 0,
      // 审批表格数据
      examineList: [],
      // 审批状态字典
      exaStateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        exaLoaId: null,
        exaName: null,
        exaTime: null,
        exaState: null,
        loaNo: null
      }
    };
  },
  created() {
    // 初始化加载审批列表和基础数据
    this.getList();
    this.getExaStateDict();
    this.getLoansNoList();
  },
  methods: {
    /** 查询审批列表 */
    getList() {
      this.loading = true;
      listExamine(this.queryParams)
        .then(response => {
          this.examineList = response.rows || [];
          this.total = response.total || 0;
        })
        .catch(error => {
          this.$message.error("获取审批列表失败：" + (error.msg || error.message));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 获取审批状态字典 */
    getExaStateDict() {
      this.getDicts("sys_loa_status")
        .then(response => {
          this.exaStateOptions = response.data || [];
        })
        .catch(error => {
          this.$message.error("获取审批状态字典失败：" + (error.msg || error.message));
        });
    },

    /** 获取贷款列表（用于关联贷款编号） */
    getLoansNoList() {
      getLoansNo()
        .then(response => {
          this.loansNoOptions = response.data || [];
        })
        .catch(error => {
          this.$message.error("获取贷款编号列表失败：" + (error.msg || error.message));
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },

    /** 根据贷款ID获取贷款编号（核心关联逻辑） */
    getLoaNoByLoaId(loaId) {
      if (!loaId) return null;
      // 从贷款列表中找到匹配loaId的记录，返回对应的loaNo
      const matchLoan = this.loansNoOptions.find(item => item.loaId === loaId);
      return matchLoan ? matchLoan.loaNo : null;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm("是否确认导出所有符合条件的审批数据？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportLoading = true;
          return exportExamine(this.queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.$message.success("导出成功");
        })
        .catch(() => {})
        .finally(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.el-table {
  margin-top: 8px;
}
.el-row {
  margin-bottom: 8px;
}
</style>
